package com.qf.qflivehou.service.serviceImpl;

import com.qf.qflivehou.config.RedisKey;
import com.qf.qflivehou.mapper.QfCourseDao;
import com.qf.qflivehou.mapper.QfOrderDao;
import com.qf.qflivehou.mapper.repository.OrderRepository;
import com.qf.qflivehou.mapper.repository.QfOrderDetailRepository;
import com.qf.qflivehou.pojo.reqVo.OrderReq;
import com.qf.qflivehou.pojo.reqVo.OrderReq2;
import com.qf.qflivehou.pojo.respVo.OrderResp;
import com.qf.qflivehou.pojo.respVo.ResponseData;
import com.qf.qflivehou.pojo.vo.LiveUser;
import com.qf.qflivehou.pojo.vo.QfOrder;
import com.qf.qflivehou.pojo.vo.QfOrderDetail;
import com.qf.qflivehou.service.OrderService;
import com.qf.qflivehou.service.UserService;
import com.qf.qflivehou.utils.GenerateOrderNum;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @author Mr.Liu
 * @date 2022/1/12 19:58
 */
@Service
@Transactional
public class OrderServiceImpl implements OrderService {

    @Resource
    private QfCourseDao qfCourseDao;
    @Autowired
    private UserService userService;
    @Resource
    private QfOrderDao qfOrderDao;
    @Autowired
    private QfOrderDetailRepository qfOrderDetailRepository;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private OrderRepository orderRepository;

    @Override
    public ResponseData addOrder(OrderReq orderReq, HttpServletRequest request) {
        //1.判断订单是否为空
        if(orderReq.getIds()==null || orderReq.getIds().size()<=0){
            return new ResponseData(1,"订单为空,请先选择需要的课程",null,null);
        }
        //2.判断订单金额是否正确
        if(orderReq.getMoney()==null || orderReq.getMoney()<=0.0){
            return new ResponseData(1,"订单金额有误",null,null);
        }
        //3.校验用户登录状态
        ResponseData responseData = userService.findUserByToken(request);
        LiveUser liveUser = (LiveUser) responseData.getData();
        if(responseData.getCode()==1){
            return responseData;
        }
        //4.核对前台传输的金额是否和数据库查询的一致
        Double money = qfCourseDao.findTotalMoney(orderReq.getIds());
        if (!orderReq.getMoney().toString().equals(money.toString())){
            return new ResponseData(1,"订单金额有误,请重新提交",null,null);
        }
        //5.开始添加订单
            //添加订单
        QfOrder qfOrder = new QfOrder();
        String orderid = GenerateOrderNum.generate("");
        qfOrder.setOrderid(orderid);
        qfOrder.setUserid(liveUser.getUserId());
        qfOrder.setCreatetime(new Date());
        qfOrder.setOrderPay(money);
        qfOrder.setOrderStatus(1);
        qfOrderDao.insert(qfOrder);
            //添加订单项
        for (Integer id : orderReq.getIds()){
            QfOrderDetail qfOrderDetail = new QfOrderDetail();
            qfOrderDetail.setOrderDetailId(GenerateOrderNum.generate(""));
            qfOrderDetail.setOrderid(orderid);
            qfOrderDetail.setCourseid(id.toString());
            qfOrderDetail.setCreatetime(new Date());
            qfOrderDetailRepository.save(qfOrderDetail);
            //生成订单后,删除购物车中的该商品
            redisTemplate.opsForHash().delete(RedisKey.SHOPCART_KEY + liveUser.getUserId().toString(), id.toString());
            //删除后判断购物车是否为空,如果为空,删除掉该购物车
            Long size = redisTemplate.opsForHash().size(RedisKey.SHOPCART_KEY + liveUser.getUserId().toString());
            if(size==0){
                //为空,删掉该购物车
                redisTemplate.delete(RedisKey.SHOPCART_KEY + liveUser.getUserId().toString());
            }
        }
        return new ResponseData(0,"生成订单成功",null,null);
    }

    @Override
    public ResponseData findOrderByUserId(HttpServletRequest request) {
        ResponseData responseData = userService.findUserByToken(request);
        if(responseData.getCode()==1){
            return responseData;
        }
        LiveUser liveUser = (LiveUser) responseData.getData();
        List<OrderResp> orderResps = qfOrderDao.findOrderByUserId(liveUser.getUserId(),1);
        return new ResponseData(0,"查询成功",orderResps,null);
    }

    @Override
    public ResponseData cancelPay(OrderReq2 orderReq2) {
        Optional<QfOrder> qfOrders = orderRepository.findById(orderReq2.getOrderid());
        //判断查询的类对象是否存在,当为true时,通过get()获取对象
        if(qfOrders.isPresent()){
            QfOrder qfOrder = qfOrders.get();
            //将未支付修改为取消
            qfOrder.setOrderStatus(4);
            //执行更新
            orderRepository.saveAndFlush(qfOrder);
            //返回结果
            return new ResponseData(0,"取消订单成功",null,null);
        }
        return new ResponseData().fail();
    }

    @Override
    public ResponseData findOldOrderByUserId(HttpServletRequest request) {
        ResponseData responseData = userService.findUserByToken(request);
        if(responseData.getCode()==1){
            return responseData;
        }
        LiveUser liveUser = (LiveUser) responseData.getData();
        List<OrderResp> orderResps = qfOrderDao.findOrderByUserId(liveUser.getUserId(),null);
        return new ResponseData(0,"查询成功！",orderResps,null);
    }
}
